/*
 * @author Javier A. Ramírez M.
 * jaramirez85@yahoo.es
 */

package com.jav;

import com.jav.inter.Constantes;
import com.jav.per.Persistencia;
import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.animations.Transition;
import com.sun.lwuit.animations.Transition3D;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.geom.Dimension;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.util.Resources;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import javax.microedition.rms.RecordEnumeration;


public class CarArchivos extends Form implements Constantes{

    private static final VentanaEspera waiting = new VentanaEspera("CARGANDO...");
    private Label lb,lb2;
    private boolean existeRuta = false;
    Button b_exp1;

    public CarArchivos() {
        super("CARGUE DATOS");
        Resources res = Datos.getInstance().getRes();
        setLayout(new BorderLayout());
        setTransitionInAnimator(Transition3D.createCube(500, true));
        setTransitionOutAnimator(Transition3D.createCube(500, false));
        
        addCommand(new Command("Atrás", res.getImage("bck.png")){
             public void actionPerformed(ActionEvent evt) {
                 CapMovil.getMainForm().show();
             }
       });
       addCommand(new Command("Cargar", res.getImage("arrow_up.png")){
             public void actionPerformed(ActionEvent evt) {
                 if (!existeRuta){
                    
                    msgBox (0x8fffffff,"ERROR","Debe seleccionar el directorio para los archivos");
                    return;
                 }
                 
                 new Thread(new Runnable() {
                 public void run() {
                     waiting.showModeless();
                        try {
                            Datos.getInstance().carClientes(b_exp1.getText()+NOM_ARC_CLI);
                            lb.setText("Cargados "+Datos.getInstance().getClientes().size()+" Clientes");
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            lb.setText("ERROR: "+ ex.getMessage());
                        }
                        try {
                            Datos.getInstance().carProductos(b_exp1.getText()+NOM_ARC_PRO);
                            lb2.setText("Cargados "+Datos.getInstance().getProductos().size()+" Productos");
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            lb2.setText("ERROR: "+ ex.getMessage());
                        }
                     waiting.dispose();
                 }}).start();
                 


             }
       });

       String lbCliente = "";
       String lbProduc = "";
       if (!Datos.getInstance().isVacioCli()){
           lbCliente = "Ya hay " + Datos.getInstance().getClientes().size() + " Clientes cargados!";
       }
       if (!Datos.getInstance().isVacioPro()){
           lbProduc = "Ya hay " + Datos.getInstance().getProductos().size() + " Productos cargados!";
       }
       
       

       b_exp1 = new Button(getRuta());
       Container largest = createPair("Dir. Arc. ", b_exp1, 30);
       

       lb = new Label (lbCliente);
       lb2 = new Label (lbProduc);
       
       //b_exp1.getStyle().setBgSelectionColor(0xFF8C00);

       
       b_exp1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                Explorer e = new Explorer();
                e.show();
                if (e.getUrlFile() != null && e.getUrlFile().length() > 0){
                    b_exp1.setText(e.getUrlFile());
                    existeRuta = true;
                    try {
                        Datos.getInstance().savePatch(e.getUrlFile());
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });




       Container cnt = new Container(new BoxLayout(BoxLayout.Y_AXIS));
       cnt.addComponent(largest);
       cnt.addComponent(lb);
       cnt.addComponent(lb2);
       addComponent("Center", cnt);

    }



    private void msgBox(int color, String titulo, String msnError) {
        Command okCommand = new Command("OK");
        Transition transitionSelection = CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, true, 0);
        this.setTintColor(color);
        Dialog.show(titulo.toUpperCase(), msnError , okCommand, new Command[] {okCommand}, Dialog.TYPE_ERROR, null, 0, transitionSelection);
    }

    protected Container createPair(String label, Component c, int minWidth) {
        Container pair = new Container(new BorderLayout());
        Label lb_text =  new Label(label);
        Dimension d = lb_text.getPreferredSize();
        d.setWidth(Math.max(d.getWidth(), minWidth));
        lb_text.setPreferredSize(d);
        //lb_text.getStyle().setBgTransparency(100);
        pair.addComponent(BorderLayout.WEST,lb_text);
        pair.addComponent(BorderLayout.CENTER, c);
        return pair;
    }

    protected String getRuta(){
        Persistencia p = null;
        String ruta = "";
        try {
            p = new Persistencia(PERS_RUTA);
            RecordEnumeration re = p.getRecordStore().enumerateRecords(null,null,false);            
            while (re.hasNextElement()){

                ByteArrayInputStream bin = new ByteArrayInputStream(re.nextRecord());
                DataInputStream din = new DataInputStream(bin);
                ruta = din.readUTF();
                this.existeRuta = true;
                bin.close();
                din.close();
            }
        }
        catch (Exception e) {
            e.printStackTrace();            
        }
        finally{
            if(p != null){
                try {
                    p.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

        return ruta;
    }




}


